package Login;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginWindow extends JFrame {
    private JPanel panel;
    private JButton regbtn;
    private JLabel label1;
    private JLabel label2;
    private JLabel usernamelabel;
    private JLabel passwordlabel;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginbtn;

    public LoginWindow() {
        // 初始化组件
        $$$setupUI$$$();

        // 为登录按钮添加事件监听器
        loginbtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                char[] passwordChars = passwordField.getPassword();
                String password = new String(passwordChars);

                Connection con = null;
                PreparedStatement ps = null;
                ResultSet rs = null;
                boolean loginSuccessful = false;

                try {
                    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "mzxyy200578");
                    String sql = "SELECT * FROM user WHERE username=? AND password=?";
                    ps = con.prepareStatement(sql);
                    ps.setString(1, username);
                    ps.setString(2, password);
                    rs = ps.executeQuery();

                    if (rs.next()) {
                        loginSuccessful = true;
                        JOptionPane.showMessageDialog(null, "登录成功！");
                        // 关闭当前登录界面
                        dispose();
                    } else {
                        JOptionPane.showMessageDialog(null, "用户名或密码错误！");
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "数据库连接失败！");
                } finally {
                    try {
                        if (rs != null) rs.close();
                        if (ps != null) ps.close();
                        if (con != null) con.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }

                // 无论登录是否成功，都清除密码字段（出于安全考虑，最好在显示成功消息之前就清除）
                passwordField.setText("");
            }
        });

        //注册按钮
        regbtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                char[] passwordChars = passwordField.getPassword();
                String password = new String(passwordChars);

                if (registerUser(username, password)) {
                    JOptionPane.showMessageDialog(null, "注册成功！");
                } else {
                    JOptionPane.showMessageDialog(null, "注册失败，用户名可能已存在！");
                }

                // 清除输入字段
                usernameField.setText("");
                passwordField.setText("");
            }
        });
    }

    //注册逻辑
    private boolean registerUser(String username, String password) {
        Connection con = null;
        PreparedStatement psCheck = null;
        PreparedStatement psInsert = null;
        ResultSet rs = null;
        boolean registered = false;

        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "mzxyy200578");

            // 检查用户名是否已存在
            String sqlCheck = "SELECT COUNT(*) FROM user WHERE username=?";
            psCheck = con.prepareStatement(sqlCheck);
            psCheck.setString(1, username);
            rs = psCheck.executeQuery();

            if (rs.next() && rs.getInt(1) == 0) {
                // 用户名不存在，插入新用户
                String sqlInsert = "INSERT INTO user (username, password) VALUES (?, ?)";
                psInsert = con.prepareStatement(sqlInsert);
                psInsert.setString(1, username);
                psInsert.setString(2, password); // 注意：这里应使用加密后的密码
                int rowsAffected = psInsert.executeUpdate();
                registered = (rowsAffected > 0);
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库连接失败！");
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (psCheck != null) psCheck.close();
                if (psInsert != null) psInsert.close();
                if (con != null) con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        return registered;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("LoginWindow");

        // 创建LoginWindow实例并设置其内容面板
        LoginWindow loginWindow = new LoginWindow();
        frame.setContentPane(loginWindow.panel);

        // 设置窗口的默认关闭操作
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 设置窗口的最小尺寸
        frame.setMinimumSize(new Dimension(250, 350));

        // 设置窗口自适应大小（pack()会根据内容自动调整窗口大小）
        // 但因为设置了最小尺寸，所以窗口至少会是750x450
        frame.pack();

        // 获取屏幕尺寸
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        // 计算窗口应该出现的位置，以使其出现在屏幕中央
        int x = (screenSize.width - frame.getWidth()) / 2;
        int y = (screenSize.height - frame.getHeight()) / 2;

        // 设置窗口位置
        frame.setLocation(x, y);

        // 设置窗口可见
        frame.setVisible(true);
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        panel = new JPanel();
        panel.setLayout(new GridLayoutManager(8, 1, new Insets(0, 0, 0, 0), -1, -1));
        panel.setEnabled(true);
        panel.setBorder(BorderFactory.createTitledBorder(null, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        regbtn = new JButton();
        regbtn.setText("注册");
        panel.add(regbtn, new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        usernameField = new JTextField();
        panel.add(usernameField, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        passwordField = new JPasswordField();
        panel.add(passwordField, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        loginbtn = new JButton();
        loginbtn.setText("登录");
        panel.add(loginbtn, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        label2 = new JLabel();
        label2.setEnabled(false);
        label2.setText("未注册用户请点击下方按键");
        panel.add(label2, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
        passwordlabel = new JLabel();
        passwordlabel.setText("密码：");
        panel.add(passwordlabel, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        usernamelabel = new JLabel();
        usernamelabel.setText("用户名：");
        panel.add(usernamelabel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        label1 = new JLabel();
        label1.setText("欢迎登录");
        panel.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        passwordlabel.setLabelFor(passwordField);
        usernamelabel.setLabelFor(usernameField);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return panel;
    }


}
